from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from rest_framework.views import APIView

# Create your views here.
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import constants
from users.models import User, Address
from users.serializers import CreateUserSerializer, EmailSerializer, UserAddressSerializer, \
    AddUserBrowsingHistorySerializer
from users.utils import check_verify_email_token


class UsernameCountView(APIView):
    def get(self, request, username):
        """
        获取指定用户名的用户数
        :param request: 请求对象
        :param username: 用户名
        :return: 用户名及其数量
        """
        # 根据用户到数据库中查询数量
        count = User.objects.filter(username=username).count()
        # 响应信息
        data = {
            'username': username,
            'count': count,
        }
        return Response(data)


class MobileCountView(APIView):
    def get(self, request, mobile):
        """
        获取指定手机号的用户数
        :param request: 请求对象
        :param mobile: 用户名
        :return: 用户名及其数量
        """
        # 根据手机号到数据库中查询数量
        count = User.objects.filter(mobile=mobile).count()
        # 响应信息
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


class UserView(CreateAPIView):
    """用户视图"""
    serializer_class = CreateUserSerializer


class UserDetailView(APIView):
    """用户详细信息个人中心视图"""
    # 权限判断【这个页面必须是登录后的用户才能访问到】
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取当前用户
        user = request.user

        # 响应数据
        return Response({
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'email': user.email,
            'email_active': user.email_active,
        })


class EmailView(UpdateAPIView):
    """用户邮箱保存视图"""
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """
        因为地址栏上面没有pk这个url参数，所以我们需要重写get_object方法获取指定的用户信息
        :return:
        """
        return self.request.user


class VerifyEmailView(APIView):
    def get(self, request):
        # 1. 获取token 提取里面的user.id
        try:
            token = request.query_params.get('token')
        except Exception:
            return Response({'message': '获取token失败'},status=status.HTTP_400_BAD_REQUEST)

        user_id = check_verify_email_token(token)
        if user_id is None:
            return Response({'message': 'token核对失败'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.根据id 获取用户信息
        try:
            # pk 表示当前模型中的主键字段
            user = User.objects.get(pk=user_id)
        except:
            return Response({'message': '没能获取到用户'},status=status.HTTP_400_BAD_REQUEST)

        # 3. 修改用户的邮箱激活状态
        user.email_active = True
        user.save()

        # 4.响应数据
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)


class AddressesViewSet(ModelViewSet):
    """用户的收货地址视图集"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer
    pagination_class = None
    # 查询当前用户的地址
    def get_queryset(self):
        return Address.objects.filter(is_deleted=False,user=self.request.user)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)

        user = self.request.user

        return Response({
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            "default_address_id": user.default_address,
            "addresses": serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        # 本次请求中pk值对应的收货地址
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


class UserBrowsingHistoryView(CreateAPIView):
    """用户浏览器商品的视图"""
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        s = AddUserBrowsingHistorySerializer(instance=None, data=request.data, context={'request': request, 'view':'view','format':''})
        s.save()
        """获取浏览历史记录"""
        # 从redis中获取当前用户的user_id
        user_id = request.user.id

        # 从redis获取浏览历史记录
        redis_conn = get_redis_connection("history")
        history = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        skus = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus, many=True)

        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证[在原有的jwt登陆方法中补充合并购物车功能]
    """

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        # 获取当前已经登陆的用户
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            # 补充合并购物车的代码
            merge_cart_cookie_to_redis(request, user, response)

        return response

